import axios from 'axios'
import { Message, MessageBox, Loading, Notification } from 'element-ui'
import qs from 'qs'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5000 * 12 * 10, // 请求超时时间
  headers: {
    'Cache-Control': 'no-cache',
    'X-Requested-With': 'XMLHttpRequest' // axios请求头部不自带头部‘X-Requested-With’的，所以要加一句默认为异步请求：
  }

})
// request拦截器
service.interceptors.request.use(
  config => {
    // config.params = {
    //   _t: Date.parse(new Date()) / 1000,
    //   ...config.params
    // }
    // if (localStorage.token) {
    //   config.headers['X-Auth-Token'] = localStorage.token // 让每个请求携带自定义token 请根据实际情况自行修改
    // }
    // 处理querystring数组参数
    if (config.method === 'get') {
        config.params.messagetoken = localStorage.token
        config.paramsSerializer = params => {
            return qs.stringify(params, { indices: false })
        }
    } else {
      config.data.messagetoken = localStorage.token
    }

    config.headers['Content-type'] = 'application/json;charset=UTF-8'
    // config.headers['content-type'] = 'application/x-www-form-urlencoded'
    // config.data = toQueryString(config.data)
    // showFullScreenLoading()
    return config
  },
  error => {
    // Do something with request error
    // tryHideFullScreenLoading()
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(

  response => {
    /**
     * status = true|false
     **/

    var res = response.data
    if (res.code != 200) {
        // location.reload() // 为了重新实例化vue-router对象 避免bug
        localStorage.setItem('token', '')
        Notification.error({
            message: res.message,
            duration: 3000
          })
        return Promise.reject('error')
    } else {
      console.log('返回数据',res.data)
      return res.data
    }

  },
  error => {
    var code = error.response ? error.response.data.code : -1
    // tryHideFullScreenLoading()
    console.log('err' + error) // for debug
    if (code === 404) {
      Notification.error({
        message: '找不到资源',
        duration: 3000
      })
    }
    return Promise.reject(error)
  }
)

export default service
